﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;

namespace Tutorials
{
    public sealed partial class FpsCounter : Microsoft.Xna.Framework.DrawableGameComponent
    {

        int frameRate = 0;
        int frameCounter = 0;
        TimeSpan elapsedTime = TimeSpan.Zero;


        private static readonly TimeSpan Second = new TimeSpan(0, 0, 1);

        /// <summary>
        /// Returns current frames per second
        /// </summary>
        public int Fps
        {
            get
            {
                return frameRate;
            }
        }

        public FpsCounter(Game game)
            : base(game)
        {

        }


        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {

            base.Initialize();
        }


        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Draw(GameTime gameTime)
        {
            elapsedTime += gameTime.ElapsedGameTime;

            if (elapsedTime > Second)
            {
                elapsedTime -= Second;
                frameRate = frameCounter;
                frameCounter = 0;
            }

            frameCounter++;

            base.Draw(gameTime);
        }

        /// <summary>
        /// Returns string representation, like FPS: 101
        /// </summary>
        public override string ToString()
        {
            return "FPS: " + Fps;
        }
    }
}
